package com.prism.e4.rcp.ui.handlers;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import javax.inject.Inject;
import javax.inject.Named;

import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import com.prism.e4.rcp.ui.parts.E4PrismEditor;
import com.prism.e4.rcp.prism.PrismException;

public class OpenEditorHandler {

	private static final String[] FILTER_NAMES = {
			"PRISM models (*.prism, *.pm, *.nm, *.sm)", "PEPA models (*.pepa)",
			"All Files (*.*)" };

	private static final String[] FILTER_EXT = { "*.prism; *.pm; *.nm; *.sm",
			"*.pepa", "*.*" };

	String fileToOpen = "";

	@Execute
	public void execute(
			@Named(IServiceConstants.ACTIVE_SHELL) Shell parentShell,
			MApplication application, EModelService modelService,
			final EPartService partService, final IWorkspace workspace,
			final IProgressMonitor monitor) {

		MPart existedPart = (MPart) modelService.find(
				"com.prism.e4.rcp.inputpart", application);
		if (!existedPart.isVisible())
			existedPart.setVisible(true);
		E4PrismEditor editor = (E4PrismEditor) existedPart.getObject();

		if (editor.dirty.isDirty()) {
			MessageDialog dialog = new MessageDialog(parentShell, "Question",
					null, "Model has been modified. Do you wish to save it?",
					MessageDialog.QUESTION, new String[] { "Yes", "No",
							"Cancel" }, 0);
			int returnCode = dialog.open();
			if (returnCode == 0) {
				FileDialog fDialog = new FileDialog(parentShell, SWT.SAVE);
				fDialog.setFilterNames(new String[] { "All Files (*.*)" });
				fDialog.setFilterExtensions(new String[] { "*.*" });
				String fileName = fDialog.open();
				if (fileName == null)
					return;
				if (new File(fileName).exists()) {
					MessageBox mb = new MessageBox(fDialog.getParent(),
							SWT.ICON_WARNING | SWT.YES | SWT.NO);
					mb.setMessage(fileName
							+ " already exists, do you want to replace it?");
					if (mb.open() == SWT.NO)
						return;
				}
			}
		}

		FileDialog dlg = new FileDialog(parentShell, SWT.MULTI);
		dlg.setFilterNames(FILTER_NAMES);
		dlg.setFilterExtensions(FILTER_EXT);
		String fileName = dlg.open();
		if (fileName != null) {
			StringBuffer buf = new StringBuffer();
			String[] files = dlg.getFileNames();
			for (int i = 0, n = files.length; i < n; i++) {
				buf.append(dlg.getFilterPath());
				if (buf.charAt(buf.length() - 1) != File.separatorChar) {
					buf.append(File.separatorChar);
				}
				buf.append(files[i]);
				buf.append("");
			}
			fileToOpen = buf.toString();
			try {
				editor.styledText.setText(new Scanner(new File(fileName))
						.useDelimiter("\\A").next());
			} catch (IOException e) {
				MessageDialog.openError(parentShell, "Error opening file",
						"File " + fileName + " could not be opened.");
			}

			loadModel(new File(fileName));
			existedPart
					.setLabel(fileName.substring(fileName.lastIndexOf("\\") + 1));
			editor.dirty.setDirty(false);
		} else
			return;
	}

	private void loadModel(File file) {
		String name = file.getName();
		if (name.endsWith("pm") | name.endsWith("nm") | name.endsWith("sm"))
			loadPRISMModel(file);
	}

	private void loadPRISMModel(File file) {
		// lastError = "";
		// Thread t = new LoadPRISMModelThread(this, editor, f, false);
		// t.start();
	}

	static String readFile(File file) throws IOException {
		Scanner scanner = new Scanner(file);
		String text = scanner.useDelimiter("\\A").next();
		scanner.close();
		return text;
	}

}
